package server.email;

import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncodingUtils {

	private static final String ALGO = "DES";
	private static Key key = new SecretKeySpec("p@Ssw0rd".getBytes(), ALGO);

	public static String encrypt(String income) throws Exception {
		byte[] encVal = getCipher(ENCRYPT_MODE).doFinal(income.getBytes());
		return new BASE64Encoder().encode(encVal);
	}

	public static String decrypt(String income) throws Exception {
		byte[] decordedValue = new BASE64Decoder().decodeBuffer(income);
		byte[] decValue = getCipher(DECRYPT_MODE).doFinal(decordedValue);
		return new String(decValue);
	}

	private static Cipher getCipher(int decryptMode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
		Cipher cipher = Cipher.getInstance(ALGO);
		cipher.init(decryptMode, key);
		return cipher;
	}

	public static String encodePath(String income) {
		try {
			return encrypt(income);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String decodePath(String income) {
		try {
			return decrypt(income);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
